﻿using System;
using System.Linq;
using System.ComponentModel;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Controls;
using System.Collections.Generic;
using QuanLyTiemThuocTay.cls;
using System.Windows.Forms;

namespace QuanLyTiemThuocTay.GiaoDien
{
    public partial class frmDonViTinh : DevExpress.XtraEditors.XtraForm
    {
        QLTTDataContext db = new QLTTDataContext();
        private int maloi;
        List<DVTINHCHECK> ListDVTINHCHECK = new List<DVTINHCHECK>();
        public frmDonViTinh()
        {
            InitializeComponent();
        }

        private void btDong_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Close();
        }

        private void frmDonViTinh_Load(object sender, EventArgs e)
        {
            btMoi.Enabled = btXoa.Enabled = btSua.Enabled = true;
            btLuu.Enabled = false;
            colTenDVTinh.OptionsColumn.ReadOnly = true;
            LoadData();
        }

        private void LoadData()
        {
            DVTINHCHECK dvtcheck;
            ListDVTINHCHECK = new List<DVTINHCHECK>();
            foreach (var item in db.DVTINHs.ToList())
            {
                dvtcheck = new DVTINHCHECK();
                dvtcheck.Check = false;
                dvtcheck.MaDVTinh = item.MaDVTinh;
                dvtcheck.TenDVTinh = item.TenDVTinh;
                ListDVTINHCHECK.Add(dvtcheck);
            }
            gc.DataSource = new BindingList<DVTINHCHECK>(ListDVTINHCHECK);
            gv.RefreshData();
        }

        private void btMoi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gv.AddNewRow();
            gv.FocusedColumn = colTenDVTinh;
            gv.FocusedRowHandle = GridControl.NewItemRowHandle;
            gv.ShowEditor();
            btLuu.Enabled = true;
            btSua.Enabled = btXoa.Enabled = false;
            colTenDVTinh.OptionsColumn.ReadOnly = false;
        }

        private void gv_InvalidValueException(object sender, DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e)
        {
            GridView v = sender as GridView;
            if (v.FocusedColumn.FieldName == "TenDVTinh")
            {
                if (maloi == 1)
                {
                    e.ExceptionMode = ExceptionMode.DisplayError;
                    e.ErrorText = "Dữ liệu phải dài hơn 2 ký tự";
                }
                else if (maloi == 2)
                {
                    e.ExceptionMode = ExceptionMode.DisplayError;
                    e.ErrorText = "Dữ liệu đã có trong hệ thống";
                }
            }
        }

        private void gv_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e)
        {
            GridView v = sender as GridView;
            if (v.FocusedColumn != colTenDVTinh)
                return;
            else
            {
                if (e.Value == null || e.Value.ToString().Length < 2)
                {
                    maloi = 1;
                    e.Valid = false;
                    return;
                }
                string giatrimoi = e.Value.ToString();
                if (v.FocusedRowHandle == GridControl.NewItemRowHandle)
                {
                    for (int i = 0; i < gv.RowCount - 1; i++)
                    {
                        var a = db.DVTINHs.FirstOrDefault(x => x.TenDVTinh == giatrimoi);
                        if (a != null)
                        {
                            maloi = 2;
                            e.Valid = false;
                            return;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < gv.RowCount; i++)
                    {
                        var b = gv.GetRow(i) as DVTINH;
                        if (giatrimoi == b.TenDVTinh && i != gv.FocusedRowHandle)
                        {
                            maloi = 2;
                            e.Valid = false;
                            return;
                        }
                    }
                }
            }
        }

        private void btLuu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gv.CloseEditor();
            gv.MoveFirst();
            for (int i = 0; i < gv.RowCount; i++)
            {
                var dulieumoi = gv.GetFocusedRow() as DVTINH;
                if (dulieumoi != null)
                {
                    if (dulieumoi.MaDVTinh != 0)
                    {
                        db = new QLTTDataContext();
                        var dulieucu = db.DVTINHs.SingleOrDefault(x => x.MaDVTinh == dulieumoi.MaDVTinh);
                        if (dulieumoi.TenDVTinh != dulieucu.TenDVTinh)
                        {
                            dulieucu.TenDVTinh = dulieumoi.TenDVTinh;
                            db.SubmitChanges();
                            clsHam.HienThi(Text, "Cập nhật thành công: " + dulieucu.TenDVTinh);
                        }
                    }
                    else
                    {
                        if (dulieumoi.TenDVTinh != null && dulieumoi.TenDVTinh.Length >= 2)
                        {
                            var ins = new DVTINH();
                            ins.TenDVTinh = dulieumoi.TenDVTinh;
                            db.DVTINHs.InsertOnSubmit(ins);
                            db.SubmitChanges();
                            clsHam.HienThi(Text, "Thêm mới thành công: " + ins.TenDVTinh);
                        }
                    }
                }
                gv.MoveNext();
            }
            LoadData();
            btMoi.Enabled = btXoa.Enabled = btSua.Enabled = true;
            btLuu.Enabled = false;
            colTenDVTinh.OptionsColumn.ReadOnly = true;
            gv.MoveLast();
        }

        private void btXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            bool cochonxoa = false;
            gv.CloseEditor();
            for (int i = 0; i < gv.RowCount; i++)
            {
                if ((gv.GetRow(i) as DVTINHCHECK).Check)
                {
                    cochonxoa = true;
                    break;
                }
            }
            if (cochonxoa && MessageBox.Show("Bạn có chắn chắn xóa những mục đã chọn?", "Xác nhận xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                for (int i = 0; i < gv.RowCount; i++)
                {
                    var donghientai = gv.GetRow(i) as DVTINHCHECK;
                    if (donghientai.Check)
                    {
                        var itemxoa = db.DVTINHs.SingleOrDefault(x => x.MaDVTinh == donghientai.MaDVTinh);
                        if (itemxoa != null)
                        {
                            try
                            {
                                db.DVTINHs.DeleteOnSubmit(itemxoa);
                                db.SubmitChanges();
                                clsHam.HienThi(Text, "Xóa thành công: " + itemxoa.TenDVTinh);
                            }
                            catch
                            {
                                MessageBox.Show("Có lỗi xảy ra đối với mục: " + itemxoa.TenDVTinh + ". \n Phục hồi thông tin.", "Không thể xóa", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
                LoadData();
            }
        }

        private void btSua_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            colTenDVTinh.OptionsColumn.ReadOnly = false;
            btMoi.Enabled = btXoa.Enabled = false;
            btLuu.Enabled = true;
        }

        private void btnNap_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            colTenDVTinh.OptionsColumn.ReadOnly = true;
            btMoi.Enabled = btXoa.Enabled = btSua.Enabled = true;
            btLuu.Enabled = false;
        }

        private void btPhieuTruoc_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!gv.IsFirstRow)
                gv.MovePrev();
        }

        private void btPhieuTiepTheo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!gv.IsLastRow)
                gv.MoveNext();
        }

        private void btTroGiup_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            MessageBox.Show("Chức năng đang xây dựng.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btIn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            colCheck.Visible = false;
            SaveFileDialog sv = new SaveFileDialog();
            sv.Filter = "Excel 97-2003|*.xls";
            sv.Title = "Lưu...";
            sv.ShowDialog();
            if (sv.FileName != "")
            {
                gv.ExportToXls(sv.FileName);
            }
            colCheck.Visible = true;
        }
    }
}